<template>
	<uni-popup ref="popup_control_play" type="bottom" border-radius="16px 16px 0 0" @change="onPopupChange">
		<view class="pop-box pad-20">
			<view class="flex flex-between flex-center">
				<view class="col-000-8 font-18 font-600">
					<!-- 播放控制 -->
					{{ $t('controlPlay.title') }}
				</view>
				<view class="close" @click="closePopup">
					<uni-icons type="closeempty" color="rgba(0,0,0,0.4)" size="20"></uni-icons>
				</view>
			</view>
			<view class="form-box">
				<view class="item m-t-20">
					<view class="title font-14 font-500 col-000-8">
						<!-- 播放速度 -->
						{{ $t('controlPlay.playSpeed') }}
					</view>
					<view class="font-14 col-000-8">
						{{speed}}%
					</view>
				</view>
				<view class="light-change">
					<slider style="margin: 10px 0;" class="audio-slider" activeColor="rgba(0,0,0,0.08)" block-size="20"
						backgroundColor="rgba(0,0,0,0.08)" block-color="#000" :value="speed" :min="play.min_value" :max="play.max_value"
						@change="handleChangeSpeed"></slider>
				</view>
				<view class="flex flex-between flex-center m-t-4">
					<view class="font-11 col-000-4">
						<!-- 慢 -->
						{{ $t('controlPlay.slow') }}
					</view>
					<view class="font-11 col-000-4">
						<!-- 快 -->
						{{ $t('controlPlay.fast') }}
					</view>
				</view>

				<view class="item m-t-20">
					<view class="title font-14 font-500 col-000-8">
						<!-- 播放完成后暂停 -->
						{{ $t('controlPlay.playPause') }}
					</view>
					<view class="font-14 col-000-8">
						<switch :checked="pause_after_complete" style="transform:scale(0.9)" color="rgba(0,0,0,0.8)"
							@change="handlePauseAfterCompleteChange" />
					</view>
				</view>

				<view class="item m-t-20">
					<view class="title font-14 font-500 col-000-8">
						<!-- 暂停时长 -->
						{{ $t('controlPlay.pauseDuration') }}
					</view>
					<view class="font-14 col-000-8">
						{{pause.show_value}}
					</view>
				</view>
				<view class="light-change">
					<slider :disabled="!pause_after_complete" style="margin: 10px 0;" class="audio-slider" activeColor="rgba(0,0,0,0.08)" block-size="20"
						backgroundColor="rgba(0,0,0,0.08)" :block-color="blockColor" :value="pause_duration" :min="pause.min_value" :max="pause.max_value"
						@change="handleChangePauseDuration"></slider>
				</view>
				<view class="flex flex-between flex-center m-t-4">
					<view class="font-11 col-000-4">
						1分钟
					</view>
					<view class="font-11 col-000-4">
						10分钟
					</view>
				</view>
				
				
				<view class="item m-t-20">
					<view class="title font-14 font-500 col-000-8">
						<!-- 开始新图案前清空沙盘 -->
						{{ $t('controlPlay.clearSandbox') }}
						<view class="font-11 col-000-4">
							<!-- 清空沙盘可确保新图案绘制效果更佳 -->
							{{ $t('controlPlay.clearSandboxTip') }}
						</view>
					</view>
					<view class="font-14 col-000-8">
						<switch :checked="clear_before_new" style="transform:scale(0.9)" color="rgba(0,0,0,0.8)"
							@change="handleClearBeforeNewChange" />
					</view>
				</view>

				<view class="form-btn font-14 col-fff m-t-40 flex-center-center" @click="saveSettings">
					<!-- 保存设置 -->
					{{ $t('controlPlay.saveSettings') }}
				</view>
			</view>
		</view>
	</uni-popup>
</template>

<script>
	import deviceStore from '@/store/deviceStore.js';
	import mqttApi from '@/api/my-mqtt.js';
	
	export default {
		data() {
			return {
				deviceSn: '', // 改为使用设备序列号
				deviceStatus: '',
				// 播放设置数据，字段名与数据库一致
				speed: 200, // 播放速度 (50-200)
				pause_after_complete: false, // 播放完成后暂停
				pause_duration: 5, // 暂停时长（分钟，前端显示用）
				clear_before_new: true, // 开始新图案前清空沙盘
				// UI 控制相关
				play: {
					min_value: 50,
					max_value: 200
				},
				pause: {
					show_value: '5分钟',
					min_value: 1, // 1分钟
					max_value: 10 // 10分钟
				},
				blockColor: '#000'
			}
		},
		methods: {
			//从deviceStore获取设备播放配置
			getDeviceFromStore(deviceSn) {
				const deviceStatus = deviceStore.getDeviceStatus(deviceSn);
				console.log('[PlayControl] 从deviceStore获取设备状态:', deviceStatus);
				
				if (deviceStatus) {
					this.deviceStatus = deviceStatus.online ? 1 : 0;
					
					// 获取设备的播放设置
					const playbackSettings = deviceStore.getPlaybackSettings(deviceSn);
					if (playbackSettings) {
						console.log('[PlayControl] 使用设备状态中的播放配置:', playbackSettings);
						
						this.speed = playbackSettings.speed || 100;
						this.pause_after_complete = playbackSettings.pause_after_complete || false;
						// 将数据库中的秒转换为前端显示的分钟
						this.pause_duration = playbackSettings.pause_duration ? Math.round(playbackSettings.pause_duration / 60) : 5;
						this.clear_before_new = playbackSettings.clear_before_new !== undefined ? playbackSettings.clear_before_new : true;
					} else {
						// 使用默认值
						console.log('[PlayControl] 使用默认播放配置');
						this.speed = 100;
						this.pause_after_complete = false;
						this.pause_duration = 5;
						this.clear_before_new = true;
					}
					
					// 更新UI显示
					this.updatePauseDisplay();
					this.updateBlockColor();
					
					console.log('[PlayControl] 最终UI状态:', {
						speed: this.speed,
						pause_after_complete: this.pause_after_complete,
						pause_duration: this.pause_duration,
						clear_before_new: this.clear_before_new
					});
				} else {
					console.warn('[PlayControl] 在deviceStore中未找到设备:', deviceSn);
					this.deviceStatus = 0;
					// 使用默认值
					this.speed = 100;
					this.pause_after_complete = false;
					this.pause_duration = 5;
					this.clear_before_new = true;
					this.updatePauseDisplay();
					this.updateBlockColor();
				}
			},
			
			open(deviceSn) {
				this.deviceSn = deviceSn;
				console.log('[PlayControl] 打开播放控制面板，设备SN:', deviceSn);
				this.getDeviceFromStore(deviceSn);
				this.$refs.popup_control_play.open('bottom');
			},
			
			closePopup() {
				this.deviceSn = '';
				this.deviceStatus = '';
				this.$refs.popup_control_play.close();
			},
			
			// 处理弹窗状态变化
			onPopupChange(e) {
				const isOpen = e.show;
				console.log('[PlayControl] 弹窗状态变化:', isOpen ? '打开' : '关闭');
				
				// 通知父组件弹窗状态变化
				if (!isOpen) {
					this.$emit('close');
				}
				
				// iOS 端处理背景滚动
				// #ifdef APP-PLUS
				const pages = getCurrentPages();
				const currentPage = pages[pages.length - 1];
				if (currentPage) {
					if (isOpen) {
						// 弹窗打开时，禁止背景页面滚动
						currentPage.$el.style.overflow = 'hidden';
					} else {
						// 弹窗关闭时，恢复背景页面滚动
						currentPage.$el.style.overflow = '';
					}
				}
				// #endif
			},
			// 播放速度改变
			handleChangeSpeed(e) {
				this.speed = e.detail.value;
			},
			// 播放完成后暂停开关改变
			handlePauseAfterCompleteChange(e) {
				this.pause_after_complete = e.detail.value;
				this.updateBlockColor();
			},
			// 暂停时长改变
			handleChangePauseDuration(e) {
				this.pause_duration = e.detail.value;
				this.updatePauseDisplay();
			},
			// 开始新图案前清空沙盘开关改变
			handleClearBeforeNewChange(e) {
				this.clear_before_new = e.detail.value;
			},
			// 更新暂停时长显示
			updatePauseDisplay() {
				this.pause.show_value = this.formatMinutesToHours(this.pause_duration);
			},
			// 更新滑块颜色
			updateBlockColor() {
				this.blockColor = this.pause_after_complete ? '#000' : '#EAEAEA';
			},
			// 封装分钟转小时和分钟的方法
			formatMinutesToHours(minutes) {
				if (minutes < 60) {
					return minutes + '分钟';
				}
				const hours = Math.floor(minutes / 60);
				const remainingMinutes = minutes % 60;
				if (remainingMinutes === 0) {
					return hours + '小时';
				}
				return hours + '小时' + remainingMinutes + '分钟';
			},
			// 保存设置
			async saveSettings() {
				if (!this.deviceSn) {
					uni.showToast({
						title: '设备序列号不能为空',
						icon: 'none'
					});
					return;
				}

				try {
					uni.showLoading({
						title: '保存中...'
					});

					// 准备播放控制配置数据
					const playbackConfig = {
						speed: this.speed,
						pause_after_complete: this.pause_after_complete,
						pause_duration: this.pause_duration * 60, // 转换为秒
						clear_before_new: this.clear_before_new
					};

					console.log('[PlayControl] 发送播放控制设置:', playbackConfig);

					// 通过MQTT发送播放控制设置
					const result = await mqttApi.sendPlaybackControl(this.deviceSn, playbackConfig);

					uni.hideLoading();

					if (result) {
						// 更新本地状态到deviceStore（合并到playback对象中）
						const currentStatus = deviceStore.getDeviceStatus(this.deviceSn) || {};
						const currentPlayback = currentStatus.playback || {};
						
						deviceStore.updateDeviceStatus(this.deviceSn, {
							...currentStatus,
							playback: {
								...currentPlayback,
								...playbackConfig
							}
						});

						uni.showToast({
							title: '设置保存成功',
							icon: 'success'
						});
						this.closePopup();
						// 触发父组件刷新
						this.$emit('refresh');
					} else {
						uni.showToast({
							title: '设置失败，请重试',
							icon: 'none'
						});
					}
				} catch (error) {
					uni.hideLoading();
					console.error('[PlayControl] 保存播放设置失败:', error);
					uni.showToast({
						title: '网络错误，请重试',
						icon: 'none'
					});
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.pop-box {
		width: 100%;
		background-color: #F3F3F3;
		border-top-left-radius: 32rpx;
		border-top-right-radius: 32rpx;
	}

	.form-box {
		width: 100%;
		margin-top: 80rpx;

		.item {
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: space-between;
		}
			   .form-btn {
				   width: 100%;
				   height: 100rpx;
				   background: #000000;
				   border-radius: 16rpx;
				   display: flex;
				   justify-content: center;
				   align-items: center;
			   }
	}
</style>